from datetime import datetime

from django.shortcuts import render

# Create your views here.
# GET /usernames/(?P<username>\w{5,20})/count/
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet, GenericViewSet
from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.views import ObtainJSONWebToken, jwt_response_payload_handler

from cart.utils import merge_cookie_cart_to_redis
from goods.models import SKU
from goods.serializers import SKUSerializer
from users import constants
from users.models import User
import logging

from users.serializers import UserSerializer, UserDetailSerializer, EmailSerializer, AddressSerializer, \
    AddressTitleSerializer, BrowseHistorySerializer

logger = logging.getLogger('django')


# class UserView(CreateAPIView):
class UserView(GenericAPIView):
    # 创建序列化器
    # 指定序列化器对象
    serializer_class = UserSerializer

    def post(self, request):
        # 获取信息并进行参数校验
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 保存数据
        serializer.save()

        return Response(serializer.data, status=status.HTTP_201_CREATED)


class UserCountView(APIView):
    def get(self, request, username):
        """查看用户是否存在"""
        # 查询数据库

        count = User.objects.filter(username=username).count()

        response_data = {
            'username': username,
            'count': count
        }
        return Response(response_data)


class MobileCountView(APIView):
    def get(self, request, mobile):
        """查看手机号是否存在"""
        # 查询数据库
        count = User.objects.filter(mobile=mobile).count()

        response_data = {
            'mobile': mobile,
            'count': count
        }
        return Response(response_data)


# class UserdetailView(GenericAPIView):
#     # 设置当前视图的访问权限（只有认证过的用户才能进行访问）
#     permission_classes = [IsAuthenticated]
#     serializer_class = UserDetailSerializer
#     def get(self, request):
#         """
#         用户中心
#         request.user:
#             1、如果用户认证过 request.user就是登录的用户对象
#             2、如果用户没有认证过 request.user就是匿名用户类对象
#         获取用户基本登录信息：
#         1、获取用户登录
#         2、将登录用户的对象序列化并返回
#         """
#         # 1、获取用户登录
#         user = request.user
#         # 将登录用户对象序列化并返回
#         serializer = self.get_serializer(user)
#         return Response(serializer.data)

# 上面代码的优化 用户信息显示
class UserdetailView(RetrieveAPIView):
    # 设置当前视图的访问权限（只有认证过的用户才能进行访问）
    permission_classes = [IsAuthenticated]
    serializer_class = UserDetailSerializer

    def get_object(self):
        """
        self.request request请求对象
        """
        return self.request.user


# 登录用户邮箱设置（API接口的设置及基本业务实现）
# class EmailView(GenericAPIView):
#     # 设置当前视图的访问权限（只有认证过得用户才能访问）
#     permission_classes = (IsAuthenticated)
#     serializer_class = EmailSerializer
#
#     def put(self,request):
#         """
#         登录用户基本设置：
#         1、获取参数email并进行校验 email必传 关注格式
#         2、设置登录用户的邮箱并给邮箱发送验证邮件
#         3、返回应答，邮箱设置成功
#         """
#         # 获取邮箱用户
#         user = request.user
#
#         # 获取参数email，并进行校验
#         serializer = self.get_serializer(user, data=request.data)
#         serializer.is_valid(raise_exception=True)
#
#         # 设置用户登录邮箱并发送验证邮件（update）
#         serializer.save()
#
#         # 返回应答 邮箱设置成功
#         return Response(serializer.data)
# 用户邮箱设置优化
class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    # 登录用户权限设置
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self, *args, **kwargs):
        return self.request.user


# 用户邮箱的验证  Verify校验
# PUT /emails/verifycation/?token=<加密token>
class EmailVerifyView(APIView):
    def put(self, request):
        """
        用户邮箱验证
        1、获取token值并进行校验（token必传值，解密后是否有效）
        2、设置对应用户的email_action的标记True
        3、返回应答，验证成功
        """
        # 1、获取token值并进行校验（token必传值，解密后是否有效） query_params 获取链接中的字符串
        token = request.query_params.get('token')

        if token is None:
            return Response({'message': '缺少参数'}, status=status.HTTP_400_BAD_REQUEST)
        user = User.check_verify_email_token(token)

        if user is None:
            return Response({'message': 'token值无效'}, status=status.HTTP_400_BAD_REQUEST)
        # 2、设置对应用户的email_action的标记True
        user.email_active = True
        user.save()
        # 3、返回应答，验证成功
        return Response({'message': '验证成功'})


class AddressViewSet(CreateModelMixin, GenericViewSet, UpdateModelMixin):
    permission_classes = [IsAuthenticated]
    serializer_class = AddressSerializer

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # post /addresses/
    def create(self, request):
        """新增地址保存"""
        # 0、判断用户地址数量是否超过上限  没有进行逻辑删除的
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_403_FORBIDDEN)
        # 1、获取参数并进行校验(参数完整性及手机号格式)
        # 在创建使用get_serializer时，kwargs['context'] = self.get_serializer_context()，会增加一个context字段
        # 取出user时，user = request.user
        # serializer = self.get_serializer(data=request.data)
        # serializer.is_valid(raise_exception=True)
        # # 2、保存新增地址数据
        # serializer.save()
        # # 3、将新增数据序列化返回
        # return Response(serializer.data,status=status.HTTP_201_CREATED)
        return super().create(request)

    # GET /adresses/
    def list(self, request):
        """
        request.user 取出登录用户
        获取用户的信息地址
        1、获取用户的登录数据
        2、将地址数据序列化
        3、返回响应
        """
        # 1、获取用户的登录数据
        addresses = self.get_queryset()
        # 2、将地址数据序列化
        serializer = self.get_serializer(addresses, many=True)
        # 3、返回响应
        response_data = {
            'user_id': request.user.id,
            'default_adress_id': request.user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data
        }
        return Response(response_data)

    # PUT /addresses/(?P<pk>\d+)/
    # def update(self,request,pk):
    #     """修改指定的用户地址信息"""
    #     # 1、根据pk获取对应的地址
    #     addr = self.get_object()
    #     # 2、获取参数并进行校验
    #     serializer = self.get_serializer(addr, request.data)
    #     serializer.is_valid(raise_exception=True)
    #     # 3、修改指定的地址数据 (update)
    #     serializer.save()
    #
    #     # 4 、将修改的数据序列化并返回
    #     return Response(serializer.data)

    # DELETE /address/(?P<pk>\d+)
    def destroy(self, request, pk):
        """
        删除指定的数据
        """
        # 1、根据pk取出地址数据
        address = self.get_object()
        # 2、将地址进行逻辑删除
        address.is_deleted = True
        address.save()
        # 3、返回逻辑应答 status = 204
        return Response(status=status.HTTP_204_NO_CONTENT)

    # PUT /addresses/(?P<pk>\d+)/status/  设置默认地址
    @action(methods=['put'], detail=True)
    def status(self, request, pk):
        """
        设置默认地址  request.user 获取登录用户
        1、根据pk值获取对应的地址信息
        2、将此地址设置为默认地址
        3、返回应答
        """
        # 1、根据pk值获取对应的地址信息
        address = self.get_object()
        # 2、将此地址设置为默认地址
        request.user.default_address = address
        request.user.default_address_id = address.id
        request.user.save()
        # 3、返回应答
        return Response({'message': 'OK'})

    # PUT /addresses/(?P<pk>\d+)/title/
    @action(methods=["put"], detail=True)
    def title(self, request, pk):
        """
        修改指定地址的标题
        1、根据pk获取地址信息
        2、获取并校验title
        3、修改标题题目
        4、返回应答
        """
        # 1、根据pk获取地址信息
        address = self.get_object()
        # 2、获取并校验title
        serializer = AddressTitleSerializer(address, request.data)
        serializer.is_valid(raise_exception=True)
        # 3、修改标题题目
        serializer.save()
        # 4、返回应答
        return Response(serializer.data)


# 用户浏览信息
# /browse_histories/  POST
# class BrowseHistoryView(GenericAPIView):
#     # 认证
#     permission_classes = [IsAuthenticated]
#     serializer_class = BrowseHistorySerializer
#
#     def post(self, request):
#         """
#         将用户信息保存起来
#         1、获取用户的sku_id 并进行校验（sku_id必传，sku_id对应的商品是否存在）
#         2、在redis中保存用户登录用户的浏览记录
#         3、返回应答，保存成功
#         """
#
#         # 1、获取用户的sku_id 并进行校验（sku_id必传，sku_id对应的商品是否存在）
#         serializer = self.get_serializer(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         # 2、在redis中保存用户登录用户的浏览记录
#         serializer.save()
#         # 3、返回应答，保存成功
#         return Response(serializer.data)

# 升级1 浏览记录
class BrowseHistoryView(CreateAPIView):
    """浏览记录保存"""
    # 认证
    permission_classes = [IsAuthenticated]
    serializer_class = BrowseHistorySerializer

    # 获取用户浏览记录
    def get(self,request):

        # 获取登录用户
        user = request.user

        # 1、从redis中取出登录用户的浏览的商品id
        # 建立连接
        redis_conn = get_redis_connection('histories')

        # 2、根据商品id获取对应的商品数据
        # 拼接获取键
        history_key = 'history_%s' % user.id
        # 根据键取值
        sku_ids = redis_conn.lrange(history_key, 0, -1)

        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        # 3、将商品信息序列化返回
        serializer = SKUSerializer(skus, many=True)
        return Response(serializer.data)


class UserAuthorizeView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            # 校验成功，账号密码正确
            user = serializer.object.get('user') or request.user
            token = serializer.object.get('token')
            response_data = jwt_response_payload_handler(token, user, request)
            response = Response(response_data)
            if api_settings.JWT_AUTH_COOKIE:
                expiration = (datetime.utcnow() +
                              api_settings.JWT_EXPIRATION_DELTA)
                response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                    token,
                                    expires=expiration,
                                    httponly=True)
            # 调用merge_cookie_cart_to_redis函数实现购物车的合并
            merge_cookie_cart_to_redis(request, user, response)
            return response

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)






